/*================================================================
*   文件名称：main.cpp
*   创 建 者：
*   创建日期：2018年07月20日
*   描    述：
*   
================================================================*/


#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool check(TreeNode *root, int sum, int target){
        if( !root->left && !root->right ){
            if( root->val + sum == target )
                return true;
            else
                return false;
        }

        if( root->left && check(root->left, sum + root->val, target) )
            return true;
        if( root->right && check(root->right, sum + root->val, target) )
            return true;

        return false;

    }

    bool hasPathSum(TreeNode* root, int sum) {
        if( !root )
            return false;
        
        return check(root, 0, sum);
    }
};



// best answer
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {       
        if( !root )
            return false;
        if( !root->left && !root->right )
            return root->val == sum;

        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
    }
};


